;;; guile-openai --- An OpenAI API client for Guile
;;; Copyright © 2023 Andrew Whatson <whatson@tailcall.au>
;;;
;;; This file is part of guile-openai.
;;;
;;; guile-openai is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Affero General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; guile-openai is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public
;;; License along with guile-openai.  If not, see
;;; <https://www.gnu.org/licenses/>.

(define-module (openai utils uri)
  #:use-module (srfi srfi-1)
  #:use-module (web uri)
  #:export (->uri
            ->relative-ref
            join-uri-paths
            resolve-uri-refs))

(define (->uri val)
  (or (cond ((uri? val) val)
            ((string? val) (string->uri val))
            (else #f))
      (error "Invalid uri:" val)))

(define (->relative-ref val)
  (or (cond ((relative-ref? val) val)
            ((string? val) (string->relative-ref val))
            (else #f))
      (error "Invalid relative-ref:" val)))

(define (join-uri-paths . paths)
  (string-append "/" (encode-and-join-uri-path
                      (append-map split-and-decode-uri-path paths))))

(define (resolve-uri-refs base . refs)
  (let* ((base (->uri base))
         (uris (cons base (map ->relative-ref refs)))
         (from-right (reverse uris)))
    (build-uri (uri-scheme base)
               #:userinfo (uri-userinfo base)
               #:host (uri-host base)
               #:port (uri-port base)
               #:path (apply join-uri-paths (map uri-path uris))
               #:query (any uri-query from-right)
               #:fragment (any uri-fragment from-right))))
